package com.autumn.aitraffic.controller;


import com.autumn.aitraffic.api.Result;
import com.autumn.aitraffic.domain.po.*;
import com.autumn.aitraffic.domain.vo.*;
import com.autumn.aitraffic.service.impl.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController()
@RequestMapping("/special")
public class SpecialController {
    @Autowired
    private VehicleServiceImpl vehicleService;
    @Autowired
    private SpeedingServiceImpl speedingService;
    @Autowired
    private RunRedLightServiceImpl runRedLightService;
    @Autowired
    private ReverseServiceImpl reverseService;
    @Autowired
    private PassLineServiceImpl passLineService;
    @Autowired
    private NoComityServiceImpl noComityService;
    @Autowired
    private IllegalTrackServiceImpl illegalTrackService;
    @Autowired
    private BackOffServiceImpl backOffService;
    @GetMapping
    public Result querySpecialRecord(int typeCar, int typeVio, String startDate, String endDate){
        ArrayList<SpecialRecordVo> result = new ArrayList<>();
        LocalDate date = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDateTime startTime = date.atStartOfDay();
        LocalDate enddate = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDateTime endTime = enddate.atStartOfDay();
        List<Vehicle> list;
        
        // 根据车辆类型筛选车辆
        if(typeCar==0) {
            list = vehicleService.lambdaQuery().in(Vehicle::getKind, 4, 6)
                    .between(Vehicle::getEntryTime,startTime,endTime)
                    .list();
        }
        else{
            list = vehicleService.lambdaQuery().in(Vehicle::getKind, typeCar)
                    .between(Vehicle::getEntryTime,startTime,endTime)
                    .list();
        }
        
        // 初始化统计数据
        CarVo carVo4 = new CarVo();
        carVo4.setKind(4);
        CarVo carVo6 = new CarVo();
        carVo6.setKind(6);
        
        // 如果没有车辆记录，直接返回空结果
        if (list.isEmpty()) {
            SpecialResultVo specialResultVo = new SpecialResultVo();
            ArrayList<CarVo> carVos = new ArrayList<>();
            carVos.add(carVo4);
            carVos.add(carVo6);
            specialResultVo.setCarlist(carVos);
            specialResultVo.setList(result);
            return Result.succ(null,specialResultVo);
        }
        
        // 创建已处理车辆的记录Map
        Map<String, Boolean> processedVehicles = new HashMap<>();
        
        // 处理车辆数据，根据typeVio参数进行筛选
        for (Vehicle vehicle : list) {
            boolean shouldAdd = false;
            
            // 判断是否应该添加此车辆
            if (typeVio == 0) {
                // 显示所有车辆
                shouldAdd = true;
            } else if (typeVio == 1) {
                // 只显示违规车辆
                shouldAdd = vehicle.getIsViolation() != null && vehicle.getIsViolation() == 1;
            } else if (typeVio == 2) {
                // 显示特殊车辆
                shouldAdd = true;
            }
            
            if (shouldAdd) {
                SpecialRecordVo specialRecordVo = new SpecialRecordVo();
                specialRecordVo.setName(vehicle.getCarPlate());
                specialRecordVo.setKind(vehicle.getKind());
                specialRecordVo.setOriginalImage(vehicle.getPicUrl());
                specialRecordVo.setEntryTime(vehicle.getEntryTime());
                
                // 设置违规状态和类型
                if (vehicle.getIsViolation() != null && vehicle.getIsViolation() == 1) {
                    specialRecordVo.setStatus(1);
                    specialRecordVo.setViolationType(vehicle.getViolationType());
                } else {
                    specialRecordVo.setStatus(0);
                    specialRecordVo.setViolationType(0);
                }
                
                specialRecordVo.setViolationId(vehicle.getId());
                result.add(specialRecordVo);
                
                // 记录已处理的车辆
                processedVehicles.put(vehicle.getCarPlate(), true);
            }
        }
        
        // 如果是只要违规记录统计（typeVio == 2）
        if(typeVio == 2) {
            for (SpecialRecordVo specialRecordVo : result) {
                if (specialRecordVo.getKind() == 4) {
                    carVo4.setNum1(carVo4.getNum1() + 1);
                    if (specialRecordVo.getStatus() == 0) carVo4.setNum2(carVo4.getNum2() + 1);
                }
                if (specialRecordVo.getKind() == 6) {
                    carVo6.setNum1(carVo6.getNum1() + 1);
                    if (specialRecordVo.getStatus() == 0) carVo6.setNum2(carVo6.getNum2() + 1);
                }
            }
            SpecialResultVo specialResultVo = new SpecialResultVo();
            ArrayList<CarVo> carVos = new ArrayList<>();
            carVos.add(carVo4);
            carVos.add(carVo6);
            specialResultVo.setCarlist(carVos);
            specialResultVo.setList(result);
            return Result.succ(null, specialResultVo);
        }
        
        // 对结果按时间排序
        result.sort(new Comparator<SpecialRecordVo>() {
            @Override
            public int compare(SpecialRecordVo o1, SpecialRecordVo o2) {
                return o2.getEntryTime().compareTo(o1.getEntryTime());
            }
        });
        
        // 统计车辆数据
        for (SpecialRecordVo specialRecordVo : result) {
            if (specialRecordVo.getKind() == 4) {
                carVo4.setNum1(carVo4.getNum1() + 1);
                if (specialRecordVo.getStatus() == 0) carVo4.setNum2(carVo4.getNum2() + 1);
            }
            if (specialRecordVo.getKind() == 6) {
                carVo6.setNum1(carVo6.getNum1() + 1);
                if (specialRecordVo.getStatus() == 0) carVo6.setNum2(carVo6.getNum2() + 1);
            }
        }
        
        // 返回结果
        SpecialResultVo specialResultVo = new SpecialResultVo();
        ArrayList<CarVo> carVos = new ArrayList<>();
        carVos.add(carVo4);
        carVos.add(carVo6);
        specialResultVo.setCarlist(carVos);
        specialResultVo.setList(result);
        return Result.succ(null, specialResultVo);
    }
    
    @GetMapping("getCarMsg")
    public Result querySpecialDetail(int violationType, int violationId) {
        SpecialCarVo specialCarVo = new SpecialCarVo();
        SpecialDetailVo specialDetailVo = new SpecialDetailVo();
        
        // 使用vehicleId直接查询车辆信息，包含违规类型
        Vehicle vehicle = vehicleService.getById(violationId);
        if (vehicle == null) {
            return Result.fail("未找到相关车辆信息", null);
        }
        
        // 设置基本信息
        String cross = vehicle.getIntersection().toString() + "号路口";
        specialCarVo.setCrossName(cross);
        specialCarVo.setPlateNum(vehicle.getCarPlate());
        specialCarVo.setVioTime(vehicle.getEntryTime());
        specialCarVo.setCarImage(vehicle.getPicUrl());
        specialCarVo.setCarType(vehicle.getKind());
        
        // 设置违规信息
        if (vehicle.getIsViolation() != null && vehicle.getIsViolation() == 1) {
            specialCarVo.setStatus(1);
            
            // 根据违规类型设置违规详情
            switch (vehicle.getViolationType()) {
                case 1:
                    specialCarVo.setViolationDetails("闯红灯");
                    break;
                case 2:
                    specialCarVo.setViolationDetails("未礼让行人");
                    break;
                case 3:
                    specialCarVo.setViolationDetails("超速");
                    break;
                case 4:
                    specialCarVo.setViolationDetails("未按规定路径行驶");
                    break;
                default:
                    specialCarVo.setViolationDetails("其他违规");
                    break;
            }
        } else {
            specialCarVo.setStatus(0);
            specialCarVo.setViolationDetails("未违规");
        }
        
        specialDetailVo.setCar(specialCarVo);
        return Result.succ(null, specialDetailVo);
    }
}
